﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using DesignByContract;
using MadMediaManager.Core.Interfaces.Services;
using MadMediaManager.Core.ExtensionMethods;

namespace MadMediaManager.Services
{
    public abstract class BaseIsoMounter : IIsoMounter
    {
        private readonly string _argumentsFormat;
        private readonly string _applicationName;

        protected BaseIsoMounter(string argumentsFormat, string applicationName)
        {
            _argumentsFormat = argumentsFormat;
            _applicationName = applicationName;
        }

        /// <summary>
        /// Mounts the specified image to a virtaul drive
        /// </summary>
        /// <exception cref="Win32Exception">Thrown if the the underlying mounting API is not installed.</exception>
        /// <param name="filePath">The path to the image</param>
        public void Mount(string filePath)
        {
            Check.Require(!filePath.IsNullOrEmpty(), "The filePath cannot be null or empty.");
            var argumentParamters = GetMountArguments();
            argumentParamters.Add(filePath);
            var arguments = string.Format(_argumentsFormat, argumentParamters.ToArray());
            using (var process = new Process())
            {
                process.StartInfo.FileName = _applicationName;
                process.StartInfo.Arguments = arguments;
                process.Start();
                process.Close();
            }
        }

        /// <summary>
        /// Mounts the specified image to a virtaul drive
        /// </summary>
        /// <exception cref="Win32Exception">Thrown if the the underlying mounting API is not installed.</exception>
        /// <param name="filePath">The path to the image</param>
        public void Unmount(string filePath)
        {
            Check.Require(!filePath.IsNullOrEmpty(), "The filePath cannot be null or empty.");
            var argumentParamters = GetUnmountArguments();
            argumentParamters.Add(filePath);
            var arguments = string.Format(_argumentsFormat, argumentParamters.ToArray());
            using (var process = new Process())
            {
                process.StartInfo.FileName = _applicationName;
                process.StartInfo.Arguments = arguments;
                process.Start();
                process.Close();
            }
        }

        protected abstract List<object> GetMountArguments();
        protected abstract List<object> GetUnmountArguments();
    }
}
